<template>
  <div>
    <a-row>
      <a-button type="primary" @click="showModal(false)">新增</a-button>
      <a-button type="primary" @click="showModal(true)">修改</a-button>
      <a-button type="danger" @click="removeApp">删除</a-button>
      <a-button type="primary" @click="showVersion">版本</a-button>
    </a-row>
    <a-row>
      <a-col :span="24">
        <a-table :columns="grid.columns"
                 :rowKey="record => record.id"
                 :dataSource="grid.data"
                 :pagination="grid.pagination"
                 :loading="loading"
                 @change="handleTableChange"
                 :rowSelection="grid.rowSelection"
        >
          <template slot="name" slot-scope="name">
            {{name.first}} {{name.last}}
          </template>
        </a-table>
      </a-col>
    </a-row>

    <a-modal
      title="Title"
      :visible="visible"
      :maskClosable="false"
      @ok="handleOk"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="form">
        <a-form-item
          label="名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'app',
          {rules: [{ required: true, message: '请输入应用名称' }]}
        ]"
          />
        </a-form-item>
        <a-form-item
          label="注释"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'remark',
          {rules: [{ required: false, message: '请输入注释' }]}
        ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!--版本列表-->
    <a-modal
      title="版本列表"
      :maskClosable="false"
      :visible="versionVisible"
      @cancel="versionHandleCancel"
      :destroyOnClose="true"
    >
      <a-row>
        <a-button type="primary" @click="showEditVersionModal(false)">新增</a-button>
        <a-button type="primary" @click="showEditVersionModal(true)">修改</a-button>
        <a-button type="danger" @click="removeVersion">删除</a-button>
      </a-row>
      <a-row>
        <a-table :columns="versionGrid.columns"
                 :rowKey="record => record.id"
                 :dataSource="versionGrid.data"
                 :pagination="versionGrid.pagination"
                 :loading="versionGrid.loading"
                 @change="handleVersionTableChange"
                 :rowSelection="versionGrid.rowSelection"
        >
          <template slot="name" slot-scope="name">
            {{name.first}} {{name.last}}
          </template>
        </a-table>
      </a-row>
      <template slot="footer">
        <a-button key="back" @click="versionHandleCancel">关闭</a-button>
      </template>
    </a-modal>

    <!--编辑版本-->
    <a-modal
      title="版本"
      :maskClosable="false"
      :visible="editVersionVisible"
      @ok="handleEditVersionOk"
      @cancel="editVersionHandleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="versionForm">
        <a-form-item
          label="名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'versionName',
          {rules: [{ required: true, message: '请输入名称' }]}]"
          />
        </a-form-item>
        <a-form-item
          label="创建时间"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-date-picker
            v-decorator="['createTime', config]"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
  import AFormItem from "gov-design-vue/es/form/FormItem";
  import {getFetch, postFetch} from '@/util/fetch';

  export default {
    components: {AFormItem},
    mounted() {
      this.fetch();
    },
    data() {
      return {
        grid: {
          columns: [
            {
              title: 'ID',
              dataIndex: 'id'
            }, {
              title: '名称',
              dataIndex: 'app',
            }, {
              title: '注释',
              dataIndex: 'remark',
            }
          ],
          data: [],
          selectedRows: [],
          rowSelection: {
            type: "radio",
            selectedRowKeys: [],
            onChange: this.onSelectChange,
          },
          pagination: {
            pageSize: 10,
            current: 1
          },
        },
        config: {
          rules: [{ type: 'object', required: true, message: 'Please select time!' }],
        },
        versionGrid: {
          columns: [
            {
              title: 'ID',
              dataIndex: 'id'
            }, {
              title: '名称',
              dataIndex: 'versionName',
            }, {
              title: '创建时间',
              dataIndex: 'createTime',
            }
          ],
          data: [],
          selectedRows: [],
          rowSelection: {
            type: "radio",
            selectedRowKeys: [],
            onChange: this.onVersionSelectChange,
          },
          pagination: {
            pageSize: 10,
            current: 1
          },
        },
        form: this.$form.createForm(this),
        versionForm: this.$form.createForm(this),
        loading: false,
        ModalText: 'Content of the modal',
        visible: false,
        versionVisible: false,
        editVersionVisible: false,
        confirmLoading: false,
        editApp: false,
        editVersion: false
      }
    },
    methods: {
      removeApp() {
        if (this.grid.selectedRows.length !== 1) {
          this.$message.warn("请选中一行");
          return;
        }
        const that = this;
        this.$confirm({
          title: '确认',
          content: '你确认要删除吗?',
          onOk() {
            getFetch("/api/app/" + that.grid.selectedRows[0].id + "/delete").then((data) => {
              that.fetch();
            });
          },
          onCancel() {
          },
        });
      },
      removeVersion() {
        if (this.versionGrid.selectedRows.length !== 1) {
          this.$message.warn("请选中一行");
          return;
        }
        let that = this;
        this.$confirm({
          title: '确认',
          content: '你确认要删除吗?',
          onOk() {
            getFetch("/api/version/" + that.versionGrid.selectedRows[0].id + "/delete").then((data) => {
              that.fetchVersion();
            });
          },
          onCancel() {
          },
        });
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.grid.selectedRows = selectedRows;
        this.grid.rowSelection.selectedRowKeys = selectedRowKeys;
      },
      onVersionSelectChange(selectedRowKeys, selectedRows) {
        this.versionGrid.selectedRows = selectedRows;
        this.versionGrid.rowSelection.selectedRowKeys = selectedRowKeys;
      },
      showDeployModal() {
        const that = this;
        if (this.grid.selectedRows.length === 0) {
          this.$message.warn("请选中行");
        } else if (this.grid.selectedRows.length > 1) {
          this.$message.warn("请选中一行");
        } else {
          const row = this.grid.selectedRows[0];
          setTimeout(() => {
            this.form.setFieldsValue({
              app: row.app,
              remark: row.remark
            });
          }, 0);
          that.deployVisible = true;
        }
      },
      showModal(edit) {
        if (edit) {
          this.editApp = true;
          if (this.grid.selectedRows.length === 0) {
            this.$message.warn("请选中行");
            return;
          } else if (this.grid.selectedRows.length > 1) {
            this.$message.warn("请选中一行");
            return;
          } else {
            const row = this.grid.selectedRows[0];
            setTimeout(() => {
              this.form.setFieldsValue({
                app: row.app,
                remark: row.remark
              });
            }, 0);
          }
        } else {
          this.editApp = false;
          this.form.resetFields();
        }
        this.visible = true
      },
      showVersion() {
        let that = this;
        if (this.grid.selectedRows.length !== 1) {
          this.$message.warn("请选中一行");
          return;
        }
        that.versionVisible = true;
        that.fetchVersion();
      },
      showEditVersionModal(edit) {
        if (edit) {
          this.editVersion = true;
          if (this.versionGrid.selectedRows.length !== 1) {
            this.$message.warn("请选中行");
            return;
          } else {
            let row = this.versionGrid.selectedRows[0];
            setTimeout(() => {
              this.versionForm.setFieldsValue({
                versionName: row.versionName,
              });
            }, 0);
          }
        } else {
          this.editVersion = false;
          this.versionForm.resetFields();
        }
        this.editVersionVisible = true
      },
      handleOk(e) {
        console.log("------");
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            if (this.editApp) {
              values.id = this.grid.selectedRows[0].id;
            }
            let url = "/api/app";
            if (this.editApp) {
              url += "/update";
            }
            postFetch(url, values).then((data) => {
              this.form.resetFields();
              this.visible = false;
              this.fetch();
              this.grid.rowSelection.selectedRowKeys = [];
              this.grid.selectedRows = [];
            });
          }
        });
      },
      handleEditVersionOk(e) {
        console.log("------");
        e.preventDefault();
        const that = this;
        this.versionForm.validateFields((err, values) => {
          if (!err) {
            if (this.editVersion) {
              values.id = this.versionGrid.selectedRows[0].id;
            }
            values.createTime = values.createTime.format('YYYY-MM-DD HH:mm:ss');
            let url = "/api/version";
            if (this.editVersion) {
              url += "/update";
            }
            values.app = that.grid.selectedRows[0];
            postFetch(url, values).then((data) => {
              this.versionForm.resetFields();
              this.editVersionVisible = false;
              this.fetchVersion();
              this.versionGrid.rowSelection.selectedRowKeys = [];
              this.versionGrid.selectedRows = [];
            });
          } else {
            this.$message.error("字段有错误");
          }
        });
      },
      versionHandleCancel(e) {
        console.log('Clicked cancel button');
        this.versionVisible = false;
      },
      handleCancel(e) {
        console.log('Clicked cancel button');
        this.visible = false;
      },
      editVersionHandleCancel(e) {
        console.log('Clicked cancel button');
        this.editVersionVisible = false;
      },
      handleTableChange(pagination, filters, sorter) {
        this.grid.pagination.current = pagination.current;
        this.grid.pagination.pageSize = pagination.pageSize;
        this.fetch();
      },
      handleVersionTableChange(pagination, filters, sorter) {
        this.versionGrid.pagination.current = pagination.current;
        this.versionGrid.pagination.pageSize = pagination.pageSize;
        this.fetchVersion();
      },
      fetch() {
        let that = this;
        that.loading = true;
        getFetch("/api/app?page=" + that.grid.pagination.current + "&size=" + that.grid.pagination.pageSize).then((data) => {
          const pagination = {...that.grid.pagination};
          // Read total count from server
          // pagination.total = data.totalCount;
          pagination.total = data.data.totalElements;
          that.loading = false;
          that.grid.data = data.data.content;
          that.grid.pagination = pagination;
        });
      },
      fetchVersion() {
        const that = this;
        const appId = that.grid.selectedRows[0].id;
        that.versionGrid.loading = true;
        getFetch("/api/version?app.id=" + appId + "&page=" + that.versionGrid.pagination.current + "&size=" + that.versionGrid.pagination.pageSize).then((data) => {
          const pagination = { ...that.versionGrid.pagination };
          pagination.total = data.data.totalElements;
          that.versionGrid.loading = false;
          that.versionGrid.data = data.data.content;
          that.versionGrid.pagination = pagination;
        });
      },
    },
  }
</script>
